const app = getApp()

Page({
  data: {
    userInfo: null
  },

  onLoad() {
    this.setData({
      userInfo: app.globalData.userInfo
    })
  },

  onShow() {
    // 每次显示页面时更新用户信息
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo
      })
      // 计算BMI
      this.calculateBMI()
    }
  },

  calculateBMI() {
    const { height, weight } = this.data.userInfo
    if (height && weight) {
      const heightInMeters = height / 100
      const bmi = (weight / (heightInMeters * heightInMeters)).toFixed(1)
      this.setData({
        'userInfo.bmi': bmi
      })
    }
  },

  navigateToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    })
  },

  navigateToPage(e) {
    const page = e.currentTarget.dataset.page
    const routes = {
      editProfile: '/pages/profile/edit',
      myPosts: '/pages/profile/posts',
      myRecipes: '/pages/profile/recipes',
      myFoods: '/pages/profile/foods',
      favorites: '/pages/recipe/favorites',
      history: '/pages/recipe/history',
      settings: '/pages/profile/settings'
    }

    if (routes[page]) {
      if (!app.globalData.hasLogin) {
        wx.showToast({
          title: '请先登录',
          icon: 'none'
        })
        return
      }
      wx.navigateTo({
        url: routes[page]
      })
    }
  },

  async handleLogout() {
    try {
      wx.showModal({
        title: '提示',
        content: '确定要退出登录吗？',
        success: (res) => {
          if (res.confirm) {
            // 清除本地存储
            wx.removeStorageSync('token')
            
            // 清除全局数据
            app.globalData.hasLogin = false
            app.globalData.userInfo = null
            
            // 更新页面状态
            this.setData({
              userInfo: null
            })
            
            wx.showToast({
              title: '已退出登录',
              icon: 'success'
            })
          }
        }
      })
    } catch (error) {
      wx.showToast({
        title: '退出登录失败',
        icon: 'none'
      })
    }
  }
}) 